package com.dinetech.ejecutor;

import java.util.ArrayList;

import com.dinetech.dao.SpinnerVariosAdapter;
import com.dinetech.dao.UbicacionAdapter;
import com.dinetech.dao.WSEvento;
import com.dinetech.entidades.Personal;
import com.dinetech.entidades.Session;
import com.dinetech.entidades.Ubicacion;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;

public class EventoCenso extends Fragment implements OnClickListener{
	
	private static final String ID_GALPON="0";
	Spinner cbxUbiCenso,  cbxRespCenso;
	EditText txtCantM, txtCantH, txtCantG, txtObs;
	Button btnGrabarC;
	Personal perC = Personal.getInstance();
	int idUsuario, idUbicacion, idGalpon;
	
	Session ses= Session.getInstance();
	
	public static EventoCenso newInstance (int IdGalpon){
		
		EventoCenso eventoC = new EventoCenso();
		
		Bundle bundle = new Bundle();
		bundle.putInt(ID_GALPON, IdGalpon);
		eventoC.setArguments(bundle);
		eventoC.setRetainInstance(true);
		
		return eventoC;
	}
		
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		ViewGroup view = (ViewGroup)inflater.inflate(R.layout.evento_censo,container, false);
		
		cbxUbiCenso = (Spinner)view.findViewById(R.id.cbxPozaC);
		cbxRespCenso = (Spinner)view.findViewById(R.id.cbxResponsableC);	
		txtObs = (EditText)view.findViewById(R.id.txtComentarioC);
		txtCantG = (EditText)view.findViewById(R.id.txtCantGazaposC);
		txtCantH = (EditText)view.findViewById(R.id.txtCantHembrasC);
		txtCantM = (EditText)view.findViewById(R.id.txtCantMachosC);
		btnGrabarC = (Button)view.findViewById(R.id.btnGrabarCenso);
		btnGrabarC.setOnClickListener(this);
		this.idGalpon = getArguments().getInt(ID_GALPON);
		new listarUbicacion().execute();
		llenarSpinner();
		
		txtObs.setNextFocusDownId(R.id.btnGrabarCenso);
		return view;
	}

	private void refrescarCenso(){
		
		new listarUbicacion().execute();
		llenarSpinner();
		txtObs.setText("");
		txtCantG.setText("");
		txtCantH.setText("");
		txtCantM.setText("");
	}
	
	private void llenarSpinner(){

		SpinnerVariosAdapter adaptadorRespC = new SpinnerVariosAdapter(EventoCenso.this, ses.getLISTA_RESPONSABLE());
		cbxRespCenso.setAdapter(adaptadorRespC);
		cbxRespCenso.setOnItemSelectedListener(new SpinnerListenerResp());
		
		for(int i=0; i <  adaptadorRespC.getCount(); i++){
			int idRA=(int)(long)adaptadorRespC.getItemId(i) ;
			idUsuario = perC.getIdPersonal();
			if( idRA == idUsuario){
				cbxRespCenso.setSelection(i);					
			}	        
		}
		
	}
	
	public class SpinnerListenerUbic implements OnItemSelectedListener {
	      
        public void onItemSelected(AdapterView<?> parent,
            View view, int pos, long id) {
        
            int convert=Integer.parseInt( Long.toString(id));
            idUbicacion= convert;	
                        
            if(idUbicacion==0){
				btnGrabarC.setEnabled(false);
			}
        }

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			
			
		}
	}
	
	public class SpinnerListenerResp implements OnItemSelectedListener {
	      
        public void onItemSelected(AdapterView<?> parent,
            View view, int pos, long id) {
        
            int convert=Integer.parseInt( Long.toString(id));
            idUsuario= convert;	            	         
        }

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			
			
		}
	}
	
	private class listarUbicacion extends AsyncTask<String, Void, ArrayList<Ubicacion>>{

		@Override
		protected ArrayList<Ubicacion> doInBackground(String... params) {
			ArrayList<Ubicacion> listaUbicacion;
			WSEvento wsE = new WSEvento();
			
			listaUbicacion = wsE.ubicacionPorEvento("15", idGalpon, 0, 0, 1, 0, perC.getIdSucursal());
			
			return listaUbicacion;
		}

		@Override
		protected void onPostExecute(ArrayList<Ubicacion> result) {
			super.onPostExecute(result);
			
			UbicacionAdapter adaptadorUbic = new UbicacionAdapter(EventoCenso.this, result);
			cbxUbiCenso.setAdapter(adaptadorUbic);
			cbxUbiCenso.setOnItemSelectedListener(new SpinnerListenerUbic());
			
			
			
		}
		
	}
	
	private class grabarParto extends AsyncTask<String, Void, String>{
		
		
		@Override
	    protected String doInBackground(String... urls) {

	    	WSEvento we= new WSEvento();
	    		    	
	    	String Msg = we.grabarEvento("01", "15", "0", "0", ses.obtenerFechaActual(), String.valueOf(idUbicacion), "0", Integer.parseInt(txtCantM.getText().toString()), Integer.parseInt(txtCantH.getText().toString()), Integer.parseInt(txtCantG.getText().toString()), "0", "0", "0", "0", 0, txtObs.getText().toString(), idUsuario, ses.obtenerFechaActual2(), perC.getIdPersonal(), 0, "0", perC.getIdSucursal(), idGalpon,0,0);
	    	return Msg;
	        	
	    }

	    @Override
	    protected void onPostExecute(String resultadoWS) {
	        super.onPostExecute(resultadoWS);	
	         
	        Toast msg = Toast.makeText(getActivity(), resultadoWS , Toast.LENGTH_LONG);
	        msg.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
	        msg.show();
	        refrescarCenso();
	        
	    }
	}

	@Override
	public void onClick(View v) {
		
		if(txtCantM.getText().length()==0){
			txtCantM.setText("0");
		}
		if(txtCantH.getText().length()==0){
			txtCantH.setText("0");
		}
		if(txtCantG.getText().length()==0){
			txtCantG.setText("0");
		}
		
		int cantTotal= Integer.parseInt(txtCantM.getText().toString()) + Integer.parseInt(txtCantH.getText().toString()) + Integer.parseInt(txtCantG.getText().toString());
		
		if(cantTotal < 1){
			AlertDialog.Builder alerta = new AlertDialog.Builder(getActivity());
			
			alerta.setTitle("Alerta");
			alerta.setMessage("La cantidad de animales ingresados no puede ser menor a 1");
			alerta.setPositiveButton("OK", 
					new DialogInterface.OnClickListener() {
			     public void onClick(DialogInterface dialog, int which) {
			     }
			    });
			alerta.show();
			
		}else{
			new grabarParto().execute();
		}
		txtCantM.requestFocus();
	}



}
